const app = getApp()
let recordStartX = 0, currentOffsetX = 0, curIndex = 0; 
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsNum: '', //商品数量
        allSelect: "circle",
        num: 0,
        count: 0,
        balance: 0,
        cartList:[],
        startX:0,
        startY:0
    },
    handleTouchStart(e){
      this.setData({
        startX:e.changedTouches[0].clientX,
        startY:e.changedTouches[0].clientY
      })
      //开始触摸时，重置所有删除

    },
    handleTouchMove(e){

    },
    
    change: function (e) {
      var that = this;
      var index = e.currentTarget.dataset.index;
      var select = e.currentTarget.dataset.select;
      console.log(select);
      
      var stype = select === "circle" ? "success" : "circle";
      var cartList = that.data.cartList;
      cartList[index].data.select = stype;
      
      that.setData({
        cartList: cartList
      });
      that.countNum();
      that.count();
    },
    addtion: function (e) {
        
        var that = this
        var index = e.currentTarget.dataset.index
        var num = e.currentTarget.dataset.num
        var storage=this.data.cartList[index].data.storage
        //默认99件
        if (num < storage) {
            num++
        }else{
          wx.showToast({
            title: ' 库存不足！',
            icon:"error"
          })
        }
        var cartList = that.data.cartList;
        cartList[index].data.num = num;
        that.setData({
          cartList: cartList
        })
        that.countNum()
        that.count()
    },
    inputNum: function (e) {
        var num = e.detail.value;
        this.setData({
            goodsNum: num
        })
    },
    

    //减法
    subtraction: function (e) {
        var that = this
        var index = e.currentTarget.dataset.index
        var num = e.currentTarget.dataset.num
        var cartList = that.data.cartList;
        

        if (num == 1) { //当数量为1件时，再次点击移除该商品
            wx.showToast({
              title: '不能再减了',
              duration:500
            })
        } else {
            num--
            cartList[index].data.num = num;
        }
        that.setData({
          cartList: cartList
        })
        that.countNum()
        that.count()
    },
    //全选
    allSelect: function (e) {
        var that = this
        var allSelect = e.currentTarget.dataset.select //先判断是否选中
        var newList = that.data.cartList
        // console.log(newList)
        if (allSelect == "circle") {
            for (var i = 0; i < newList.length; i++) {
                newList[i].data.select = "success"
            }
            var select = "success"
        } else {
            for (var i = 0; i < newList.length; i++) {
                newList[i].data.select = "circle"
            }
            var select = "circle"
        }
        that.setData({
            cartList: newList,
            allSelect: select
        })
        that.countNum()
        that.count()
    },

    countNum: function () { //计算数量
        var that = this
        var newList = that.data.cartList
        var allNum = 0
        for (var i = 0; i < newList.length; i++) {
            if (newList[i].data.select == "success") {
                allNum += parseInt(newList[i].data.num)
            }
        }
        that.setData({
            num: allNum
        })
    },

    count: function () { //计算金额方法
        var that = this
        var newList = that.data.cartList
        var newCount = 0
        for (var i = 0; i < newList.length; i++) {
            if (newList[i].data.select == "success") {
                newCount += newList[i].data.num * newList[i].data.price
            }
        }
        
        that.setData({
            count: newCount
        })
    },

    getcartdata() {
      var that=this
      wx.getStorage({
        key:"cartList",
        success(res) {
          that.setData({
            cartList:res.data
          })
          that.countNum()
          that.count()
        },
        fail(error) {
          console.log('读取存储数据失败：', error);
        }
      })
      
      
    },


    //判断能否购买
    judge_buy() {
        var that = this
        var balance = that.data.balance - that.data.count
        if (balance >= 0) {
            that.purchase()
        } else {
            wx.showToast({
                title: '余额不足',
                duration: 1500,
                icon: 'error'
            })
        }
    },


    //购买
    async purchase() {
      const that = this
      if (that.data.cartList.length==0) {
        wx.showToast({
          title: '未选择任何商品',
          icon:"error"
        })
      }else{
        let cartList = wx.getStorageSync('cartList') || []
        // 过滤出选中的商品
        const newlist = cartList.filter(item => item.data.select !== "success")
        const id_group=[]
        newlist.forEach(item => {
          id_group.push(item.key)
        });
        // 删除选中的商品
        cartList = cartList.filter(item => item.data.select === "success")
        wx.setStorageSync('cartList', cartList) // 更新本地存储中的购物车列表
      
        // 弹出加载框
        wx.showLoading({
          title: '购买中...',
          mask: true
        })
      
        // 延迟2秒后执行购买成功操作
        setTimeout(async function() {
          // 发送购买请求
          const result = await wx.p.request({
            url: app.globalData.url + "/shopping_cart/purchase",
            data: {
              id_group: JSON.stringify(id_group),
              p_uid: app.globalData.userInfo.uid
            },
            method: "GET"
          })
          
          
          // 隐藏加载框
          wx.hideLoading()
      
          // 展示购买成功提示
          wx.showToast({
            title: result.data.data,
            icon: 'success'
          })
          
          // 清除被选中的数组
          that.setData({
            cartList: cartList
          })
          
          // 更改余额、价格和数量
          await that.balance()
          await that.count()
          await that.countNum()
        }, 1500)
      }
      
    },

  
    //更改余额
    async balance() {
        var that = this
        var count = that.data.count
        const url = app.globalData.url + '/shopping_cart/changebalance';
        const result = await wx.p.request({
          url: url,
          method: 'GET',
          data: {
            uid: app.globalData.userInfo.uid,
            count: count
          }
        })
        app.globalData.userInfo.balance=result.data.data
        
    },

    //获取余额
    getbalance() {
        var that = this
        this.setData({
          balance:app.globalData.userInfo.balance
        })
    },

    
    

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        
        await this.getcartdata();
        await this.getbalance();
        // console.log(app.globalData.user)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      this.getcartdata()
      this.getbalance()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.getcartdata();
        this.getbalance();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

})